package co.laomag.coffee.service.user.impl;

import cn.hutool.crypto.digest.DigestUtil;
import co.laomag.coffee.dao.user.ChUserDao;
import co.laomag.coffee.dao.user.ChUserinfoDao;
import co.laomag.coffee.model.entity.ChUser;
import co.laomag.coffee.model.entity.ChUserinfo;
import co.laomag.coffee.model.vo.Message;
import co.laomag.coffee.model.vo.Pagination;
import co.laomag.coffee.service.user.UserService;
import co.laomag.coffee.utils.ResultUtils;
import co.laomag.coffee.utils.UUIDUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 马泽朋
 * @version 1.0
 * @date 2020/4/19 下午 3:21
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private ChUserDao chUserDao;

    @Resource
    private ChUserinfoDao chUserinfoDao;
    /**
     * 用户注册
     *
     * @param chUser 用户实体
     * @return 返沪大于0注册成功
     */
    @Override
    public Message addUser(ChUser chUser) {
        chUser.setPassword(DigestUtil.md5Hex(chUser.getPassword()));
        Message message = null;
        chUser.setUid(UUIDUtils.createUUID());
        int insert = chUserDao.insert(chUser);
        if (insert > 0){
            message = ResultUtils.message(200, "注册成功");
        }else {
            message = ResultUtils.message(200, "注册失败");
        }
        return message;
    }

    /**
     * 添加用户信息
     *
     * @param chUserinfo 用户信息实体
     * @return
     */
    @Override
    public Message addUserInfo(ChUserinfo chUserinfo) {
        Message message = null;
        int insert = chUserinfoDao.insert(chUserinfo);
        if (insert > 0){
            message = ResultUtils.message(200, "注册成功");
        }else {
            message = ResultUtils.message(200, "注册失败");
        }
        return message;
    }

    /**
     * 修改用户操作
     *
     * @param chUser
     * @return
     */
    @Override
    public Message updateUser(ChUser chUser) {
        chUser.setPassword(DigestUtil.md5Hex(chUser.getPassword()));
        Message message = null;
        int i = chUserDao.updateByPrimaryKeySelective(chUser);
        if (i > 0){
            message = ResultUtils.message(200, "操作成功");
        }else {
            message = ResultUtils.message(200, "操作失败");
        }
        return message;
    }

    /**
     * 获取所有用户
     *
     * @param pagination
     * @return
     */
    @Override
    public Message getUserList(Pagination pagination) {
        Message message = null;
        List<ChUser> userList = chUserDao.getUserList(pagination);
        if (userList == null || userList.size() < 0){
            message = ResultUtils.message(200, "暂无数据");
        }else {
            Map<String, Object> map = new HashMap<>(2);
            map.put("list", userList);
            int total = chUserDao.getTotal();
            map.put("total",total);
            message = ResultUtils.message(200, "查询成功",map);
        }
        return message;
    }
}
